-- UISignIn
-- Create by chendh
-- 签到界面

require "game/ui/form/hero/HeroUtil"

-- UISignIn继承自Layer
UISignIn = class("UISignIn", function()
    return cc.Layer:create();
end);

function UISignIn.create()
    return UISignIn.new();
end

-- 扈从格最大行数
local MIN_GRID_COLUMN = 3;
local MAX_GRID_ROW    = 2;
local ITEM_NAME       = "item";

-- 构造函数
function UISignIn:ctor()
    -- 初始化
    self:setName("UISignIn");
    local node = cc.CSLoader:createNode("layout/lictor/LictorChoose.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    self.CT = CT;
    local scroll_view = findChildByName(self.node, "CT/bg_1/scroll_view");
    self.scrollView = scroll_view;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.selectIndex = 1;
    local curDay = NewSignInM.getSignInDays();
    if curDay < 7 then
        self.selectIndex = curDay + 1;
    end

    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    self:initData();

    -- 初始化签到奖励格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册函数回调
function UISignIn:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISignIn 界面析构清理");
            EventMgr.removeAll("UISignIn");

            -- show bottom
            local uiTalentMain = UIMgr.getCurrentScene():getFormByName("UITalentMain");
            if uiTalentMain then
                uiTalentMain:showButtons();
            end
        elseif ev == "enter" then
            -- hide bottom
            local uiTalentMain = UIMgr.getCurrentScene():getFormByName("UITalentMain");
            if uiTalentMain then
                uiTalentMain:hideButtons();
            end
        end
    end);

    -- 关注签到奖励
    EventMgr.register("UISignIn", event.SIGN_IN_BONUS, function()
        self:redraw();
    end);
end

-- 重绘
function UISignIn:redraw()
    -- 绘制标题
    local days = NewSignInM.getSignInDays();
    local titleLabel = findChildByName(self.CT, "title/title_label");
    titleLabel:setString(string.format(getLocStr("sign_in_title"), days));
    TextStyleM.setTitleStyle(titleLabel);

    -- 绘制副标题
    local titleExplainLabel = findChildByName(self.CT, "title/title_explain");
    titleExplainLabel:setVisible(true);
    TextStyleM.setSubheadStyle(titleExplainLabel);

    if NewSignInM.canSignIn() then
        titleExplainLabel:setString(getLocStr("sign_in_subhead"));
    else
        local signInInfo = ME.user.dbase:query("sign_in_info");
        local serverTime = TimeM.getServerTime();
        local remainingTime = (signInInfo.next_time or 0) - serverTime;

        titleExplainLabel:setString(string.format(getLocStr("sign_in_remain_time"), remainingTimeDesc(remainingTime)));
    end

    -- 绘制页面
    local itemCount = #self.data;
    local index = 0;

    if not self.data or itemCount == 0 then
        cclog("收集七日签到信息失败。");
        self:clearAllGrid();
        return;
    end

    for index = 1, itemCount do
        -- 获取签到奖励格
        local child = self.scrollView:getChildByName(ITEM_NAME .. index);
        if child == nil then
            break;
        end

        -- 设置选中效果
        local focusBg = child:getChildByName("focus");
        if self.selectIndex == index then
            focusBg:setVisible(true);
        else
            focusBg:setVisible(false);
        end

        -- 背景
        local bgImg = child:getChildByName("bg");
        local bgImgGray = child:getChildByName("gray_bg");
        -- icon
        local iconImage = child:getChildByName("icon");
        -- 星级
        local starImage = child:getChildByName("rank");
        -- "已签到"的tip
        local tipImage = child:getChildByName("tip");
        -- 右上角的蓝色hint
        local hintNode = findChildByName(child, "hint");
        -- 默认全部隐藏
        bgImg:setVisible(true);
        bgImgGray:setVisible(false);
        iconImage:setVisible(false);
        starImage:setVisible(false);
        tipImage:setVisible(false);

        bgImg:loadTexture(getFrameBgIconPath("sign_in"));

        local data = self.data[index];
        if data then
            local iconPath = "";
            local bonus = data[1];
            -- 有数据
            if bonus[1] == 1 then
                -- 奖励是物品
                iconPath = getItemIconPath(bonus[2]);
                iconImage:setPositionY(0);
                iconImage:setScale(0.8);

                if not iconImage.initPosX then
                    iconImage.initPosX = iconImage:getPositionX();
                end
                iconImage:setPositionX(iconImage.initPosX + 1);
            elseif bonus[1] == 2 then
                -- 奖励是属性
                -- 设置属性图标
                iconImage:setPositionY(0);
                iconImage:setScale(0.8);
                if bonus[2] == "gem" then
                    iconPath = getItemIconPath(9999);
                else
                    iconPath = getLargeAttribIconPath(FieldsM.query(bonus[2], "icon"));
                    iconImage:setScale(1);
                    if not iconImage.initPosX then
                        iconImage.initPosX = iconImage:getPositionX();
                    end
                    iconImage:setPositionX(iconImage.initPosX + 2);
                end
            elseif bonus[1] == 3 then
                -- 奖励是宠物
                -- 设置宠物头像
                local iconIndex = PetM.getDefaultIcon(bonus[2]);
                iconPath = getHeroIconPath(iconIndex);
                iconImage:setPositionY(3);
                iconImage:setScale(1);

                -- 设置星阶
                -- 星级控件
                starImage:setVisible(true);
                local starNum = PetM.query(bonus[2], "init_rank")
                local tStar = createStarLayer(starNum,"images/ui/symbol/star_little.png", "center", -0.7);
                if tStar then
                    starImage:removeAllChildren();
                    starImage:addChild(tStar);
                end
            end

            iconImage:loadTexture(iconPath);
            iconImage:setVisible(true);

            if index <= days then
                -- 玩家已签到
                iconImage:setOpacity(255);
                bgImg:setOpacity(255);

                tipImage:loadTexture(getCornerImg("signed"));
                tipImage:setVisible(true);
            else
                iconImage:setOpacity(125.5);
                bgImg:setOpacity(125.5);
            end

            if index == days + 1 and NewSignInM.canSignIn() then
                checkBlueBubbleStatus(hintNode, true);
            else
                checkBlueBubbleStatus(hintNode, false);
            end
        end
    end

    self:refreshExplain();

    -- 设置选择按钮是否可用
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    btnSelect:setTitleText(getLocStr("sign_in"));
    btnSelect:setBright(false);
    btnSelect:setTouchEnabled(false);

    local data = self.data[self.selectIndex];
    if not data then
        return;
    end

    if self.selectIndex == days + 1 and NewSignInM.canSignIn() then
        btnSelect:setBright(true);
        btnSelect:setTouchEnabled(true);
    end

    local function tick()
        self:redraw();
    end
    performWithDelay(self, tick, 1);
end

-- 设置说明
function UISignIn:refreshExplain()
    local data = self.data[self.selectIndex];
    local days = NewSignInM.getSignInDays();
    local captionLabel = findChildByName(self.CT, "bg_2/caption_label");
    TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    local desc = "";
    local blank = "";
    if getLang() ~= "zh" and getLang() ~= "tw" then
        blank = " ";
    end
    if self.selectIndex <= days then
        desc = string.format("%s%s", getLocStr("sign_in_bonus"), getLocStr("signed"));
    elseif self.selectIndex == days + 1 and NewSignInM.canSignIn() then
        desc = string.format("%s%s[green]%s[-]", getLocStr("sign_in_bonus"), blank, getLocStr("can_sign"));
    else
        desc = string.format("%s%s[gray]%s[-]", getLocStr("sign_in_bonus"), blank, getLocStr("not_sign"));
    end
    applyString(captionLabel, desc);

    local Label = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    Label:setVisible(true);
    TextStyleM.setTextStyle(Label, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    -- 奖励描述
    local labelDesc = getLocStr("sign_in_bonus_desc") .. "\n";

    for i, v in ipairs(data) do
        local bonus = v;

        if bonus then
            if bonus[1] == 2 then
                labelDesc = labelDesc .. string.format("[blue]%s x %d[-]", FieldsM.getFieldName(bonus[2]), bonus[3]) .. "\n";
            elseif bonus[1] == 1 then
                labelDesc = labelDesc .. string.format("[blue]%s x %d[-]", ItemM.query(bonus[2], "name"), bonus[3]) .. "\n";
            elseif bonus[1] == 3 then
                labelDesc = labelDesc .. string.format("[blue]%s[-]", PetM.query(bonus[2], "name")) .. "\n";
            end
        end
    end
    applyString(Label, labelDesc);

    -- 阵营名称
    local campLabel = findChildByName(self.CT, "bg_2/camp_label");
    campLabel:setVisible(false);

    -- 徽章阵营图标
    local campIconImage = findChildByName(self.CT, "bg_2/camp_icon");
    campIconImage:loadTexture(getTalentIconPath("sign_in_big"));
    if not campIconImage.initPosY then
        campIconImage.initPosY = campIconImage:getPositionY();
        campIconImage:setPositionY(campIconImage.initPosY - 10);
    end
end

-- 初始化签到奖励数据
function UISignIn:initData()
    self.data = NewSignInM.getSignInBonus();
end

-- 初始化扈从格
function UISignIn:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 15;

    -- 图标宽度
    local iconWidth = 140;

    -- 图片高度
    local iconHeight = 125;

    local topHGap  = 20;
    local leftWGap = 20;

    local bottomHGap = 20;
    -- 收集签到奖励信息
    local bonusList = self.data;

    -- 奖励的总个数
    local bonusCount = #bonusList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/lictor/LictorItem.csb");
    local hintNode = itemNode:getChildByName("hint");
    replaceNodeWithWidget(hintNode);

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, bonusCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerItemTouchEvent);
end

-- 清空所有的单元格
function UISignIn:clearAllGrid()
    -- 格子总数
    local totalGridCount = #self.data;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName(ITEM_NAME .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 注册扈从点击事件
function UISignIn:registerItemTouchEvent(node)
    local image = node:getChildByName("bg");
    local grayImage = node:getChildByName("gray_bg");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if self.data[node.index] == nil then
                return;
            end
            local lastSelected = self.selectIndex;

            self.selectIndex = node.index;

            self:itemSelected(lastSelected, node.index);
            -- self:redraw();
        end
    end

    image:addTouchEventListener(onClick);
    grayImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UISignIn:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UISignIn");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册选择按钮点击事件
    local btnSelect = findChildByName(node, "BT/choose_btn");
    local function onSelectClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_receive");
            local data = self.data[self.selectIndex];
            if NewSignInM.canSignIn() then
                NewSignInM.signIn();
            end
        end
    end

    btnSelect:addTouchEventListener(onSelectClick);
    TextStyleM.setTextStyle(btnSelect, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnSelect:setTitleText(getLocStr("sign_in"));
end

-- 适配
function UISignIn:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");

    -- TOP顶部居中并缩放至合适大小
    --AlignM.alignToTopCenter(node, "TOP");
end

-- 扈从选中效果
function UISignIn:itemSelected(lastSelected, nowSelected)
   -- 清除上次选中效果
    local lastSel = self.scrollView:getChildByName(ITEM_NAME .. lastSelected);
    local focusBg = lastSel:getChildByName("focus");
    focusBg:setVisible(false);

    -- 新选中的效果
    local nowSel = self.scrollView:getChildByName(ITEM_NAME .. nowSelected);
    local nowFocusBg = nowSel:getChildByName("focus");
    nowFocusBg:setVisible(true);

    -- 更新说明和按钮
    self:refreshExplain();

    -- 更新选择按钮
    local data = self.data[self.selectIndex];
    local btnSelect = findChildByName(self.node, "BT/choose_btn");

    if not data then
        btnSelect:setBright(false);
        btnSelect:setTouchEnabled(false);
        return;
    end

    local days = NewSignInM.getSignInDays();
    if self.selectIndex == days + 1 and NewSignInM.canSignIn() then
        btnSelect:setBright(true);
        btnSelect:setTouchEnabled(true);
    else
        btnSelect:setBright(false);
        btnSelect:setTouchEnabled(false);
    end
end